/**
 * Created by mlr on 2016/9/6.
 */
var path = require('path')
    ,   fs   = require('fs')
    ,   Map  = {}
    ,   Load = {}
    ,   debug = process.env.NODE_ENV !== 'production';

function isArray(v){
    return Object.prototype.toString.apply(v) === '[object Array]';
}
Load.load = function(file_width_path_name){
    debug && console.log(file_width_path_name, '-----load----------');
    if(!(file_width_path_name in Map) || debug) {
        if(fs.existsSync(file_width_path_name)) {
            fs.watch(file_width_path_name, function(event,filename){
                if(event == 'change') { delete require.cache[file_width_path_name];}
            });
            Map[file_width_path_name] = require(file_width_path_name);
        } else {
            // console.error(file_width_path_name + ' not found');
            Map[file_width_path_name] = undefined;
        }
    }
    return Map[file_width_path_name];
}

Load.wrapLoad = function(name){
    return Load.load(path.join(path.dirname(name), path.basename(name, path.extname(name)))+ '.js');
};
Load.Aload = function(name){
    isArray(name) || (name = [String(name).replace(/\.\./g, '').replace(/^\//,'')]);
    name = path.resolve(APP_BASE.A, path.join.apply(path, name));
    return Load.wrapLoad(name);
};
Load.Fload = function(name){
    isArray(name) || (name = [String(name).replace(/\.\./g, '').replace(/^\//,'')]);
    name = path.resolve(APP_BASE.F, path.join.apply(path, name));
    return Load.wrapLoad(name);
};

Load.Sload = function(name){
    isArray(name) || (name = [String(name).replace(/\.\./g, '').replace(/^\//,'')]);
    name = path.resolve(APP_BASE.S, path.join.apply(path, name));
    return Load.wrapLoad(name);
}

module.exports = Load;
